<template>
	<view class="Myform bor-radius-20" :style="`background-color:${formBgColor}`">
		<up-form labelPosition="top" ref="uFormRef" :model="state.modelData" :rules="rules" v-if="state.show">
			<up-form-item v-for="(item,index) in data" :key="item.label" :prop="item.prop" :style="`margin:${margin}`"
				:label="labelFun(item)" labelWidth="200px">
				<up-input :disabled="item?.disabled" :placeholder="forMat(item)" border="none"
					v-model="state.modelData[item.prop]"
					:style="`background-color:${bgColor};padding:${padding};border:${state.key == index&&border?'1px solid #11E2BD':'none'};`"
					:password="item?.type == 'private'" :class="{'input-shadow':border}" @click.stop="click(item,index)"
					:fontSize="fontSize" :color="color">
					<template #suffix v-if="item?.type == 'private'||item.privateShow">
						<image v-if="!item.privateShow" style="width:40rpx;height:40rpx;"
							src="../../static/icon/if-eye-blocked1@3x.png" mode="" @click.stop="privateClick(item)">
						</image>
						<image v-else style="width:40rpx;height:40rpx;" src="../../static/icon/offyear.png" mode=""
							@click.stop="privateClick(item)">
						</image>
					</template>
					<template #suffix v-if="item?.type == 'Code'">
						<up-button style="width: 300rpx;height: 52rpx; " class="f-size-12 p-0" @tap="getCode(item)"
							:class="{'button':settingCode}">{{tips}}{{Number(tips)?'s':''}} </up-button>
					</template>
				</up-input>
				<up-line style="position: absolute; bottom: 0; width: 90%; left: 30rpx;" v-if="item.line"></up-line>
			</up-form-item>
		</up-form>


		<view class="Myform-bottom" v-if="illustrate">
			<up-checkbox :customStyle="{marginBottom: '8px'}" style="font-weight: 600;" :label="illustrate"
				labelSize="10" labelColor="black" name="agree" usedAlone v-model:checked="state.aloneChecked">
			</up-checkbox>
		</view>
		<up-picker :show="state.selectShow" :columns="state.selectColumns" @close="state.selectShow=false"
			@confirm="selectConfirm" @cancel="state.selectShow=false" cancelText="cancel"
			confirmText="confirm"></up-picker>
		<up-datetime-picker :hasInput="false" :show="state.dateShow" mode="date" @cancel="state.dateShow=false"
			@confirm="dateConfirm" cancelText="cancel" confirmText="confirm"></up-datetime-picker>
	</view>
</template>

<script setup>
	import {
		getEmailCodeApi
	} from '@/api/common.js'


	onMounted(() => {

		//初始化data
		initData()
		//初始化 rules
		initRules()

		//显示组件
		state.show = true
	})
	const uFormRef = ref(null);
	const state = reactive({
		aloneChecked: false,
		show: false,
		modelData: {},
		key: 0,
		selectShow: false,
		dateShow: false,
		selectColumns: [],
		currentProp: ''

	})
	const props = defineProps({
		data: {
			type: Object
		},
		formBgColor: {
			type: String,
			default: '#fff'
		},
		illustrate: { //说明文字
			type: String,
			default: ''
		},
		bgColor: {
			type: String
		},
		rules: {
			type: Object,
			default: {}
		},
		border: {
			type: Boolean,
			default: false
		},
		padding: {
			type: String,
			default: '30rpx'
		},
		margin: {
			type: String,
			// default: '30rpx 0rpx'
		},
		label: {
			type: Boolean,
			default: false
		},
		settingCode: {
			type: Boolean,
			default: false
		},
		fontSize: {
			type: [Number, String],
			// default: false,

		},
		color: {
			type: String,
			default: '#303133'
		}
	})

	// watch(() => props.data, (newValue, oldValue) => {
	// 	initData()
	// 	console.log(props.data[1].value, 'props.data');
	// }, {
	// 	deep: true
	// })


	const tips = ref('get verification code');

	const Interval = ref(null)


	const getCode = async (item) => {
		let postData = {

		}
		if (item.codeType === 'email') {
			postData.email = state.modelData[item.reference]
		}
		tips.value = 10
		Interval.value = setInterval(() => {
			if (tips.value == 1) {
				clearInterval(Interval.value)
				tips.value = 'get verification code'
			} else {
				tips.value -= 1
			}
		}, 1000)
		const {
			code,
			data
		} = await getEmailCodeApi(postData)
		uni.hideLoading()
		if (code === 200) {
			uni.$u.toast('验证码已发送');
			state.modelData[item.prop] = data
		}



	}
	//格式化placeholder
	const forMat = (item) => {
		if (item.type === 'select' || item.type === 'date') {
			return ' please select your ' + item.label
		}
		return  item.label

	}
	//初始化数据
	const initData = () => {
		console.log('init', props.data);
		let modelData = {

		}

		props.data.map(item => {
			if (item.type == 'select') {
				item.value = item.columns.find(v => v.value == item.value)?.text
			}

			modelData[item.prop] = item.value
		})
		state.modelData = modelData


	}

	//初始化校验规则
	const initRules = () => {
		if (!props.rules) {
			return
		}
		Object.keys(props.rules).forEach(item => {

			let obj = props.rules[item]
			if (uni.$u.test.object(obj) && obj.type === 0) {
				switch (obj.type) {
					//两次密码一致校验
					case 0:

						props.rules[item] = [getVerifyObj('string', true,
								'Please fill in your confrimPassword', 2),
							getVerifyFun(3, 'The password is inconsistent twice', 0, obj
								.prop)
						]
						break;
				}

			} else {
				switch (obj) {
					//邮箱校验
					case 'email':
						props.rules[item] = [getVerifyObj('string', true, 'Please fill in your email', 2),
							getVerifyFun(0, 'Please enter the correct email format', 0)
						]
						break;
						//密码校验
					case 'password':
						props.rules[item] = [getVerifyObj('string', true, 'Please fill in your Password',
								2),
							getVerifyFun(1, 'Please enter the correct password format', 0)
						]
						break;
						//验证码校验
					case 'code':
						props.rules[item] = [getVerifyObj('string', true, 'Please fill in your code', 2),
							getVerifyFun(2, 'Please enter the correct code format', 0)
						]
						break;
					case 'require':
						console.log('进来了')
						props.rules[item] = [getVerifyObj('string', true, 'Please fill in', 2)]
						break;
				}
			}
		})
	}
	const getVerifyObj = (type, required, message, trigger) => {
		let copyTrigger
		switch (trigger) {
			case 0:
				copyTrigger = ['blur']
				break;
			case 1:
				copyTrigger = ['change']
				break;
			case 2:
				copyTrigger = ['blur', 'change']
				break;
		}
		return {
			type,
			required,
			message,
			trigger: copyTrigger
		}
	}
	const getVerifyFun = (type, message, trigger, prop) => {
		let copyTrigger
		let cb
		switch (trigger) {
			case 0:
				copyTrigger = ['blur']
				break;
			case 1:
				copyTrigger = ['change']
				break;
			case 2:
				copyTrigger = ['blur', 'change']
				break;
		}
		switch (type) {
			case 0:
				//验证邮箱
				cb = (rule, value, callback) => {

					return uni.$u.test.email(value);
				}
				break;
			case 1:
				//校验密码
				cb = (rule, value, callback) => {
					let reg = /^(?=.*[a-z])(?=.*\d)[^]{8,16}$/
					return reg.test(value);

				}
				break;
			case 2:
				//验证码
				cb = (rule, value, callback) => {

					return uni.$u.test.code(value, 6);
				}
				break;
			case 3:
				cb = (rule, value, callback) => {

					return state.modelData[prop] === value;
				}
		}

		return {
			validator: cb,
			message,
			trigger: copyTrigger
		}
	}
	//返回label
	const labelFun = (item) => {
		if (props.label) {
			return item.label
		}
	}
	//点击显示密码
	const privateClick = (item) => {
		item.privateShow = item.type === 'private'
		item.type = item.type === 'private' ? 'input' : 'private'

	}
	//点击输入框
	const click = (item, index) => {

		state.key = index
		switch (item.type) {
			case 'select':
				// uni.hideKeyboard()
				state.currentProp = item.prop
				state.selectColumns[0] = item.columns
				nextTick(() => {
					state.selectShow = true
				})
				break;
			case 'date':
				uni.hideKeyboard()
				state.currentProp = item.prop
				nextTick(() => {
					state.dateShow = true
				})
		}

	}
	//选中
	const selectConfirm = (e) => {
		console.log(e.value[0]);
		state.modelData[state.currentProp] = e.value[0].text
		state.selectShow = false
	}
	//选中日期
	const dateConfirm = (e) => {
		state.dateShow = false
		state.modelData[state.currentProp] = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')

	}
	//格式化值
	const forMatValue = () => {
		let modelData = uni.$u.deepClone(state.modelData)
		for (let key in modelData) {
			props.data.forEach(item => {
				if (item.type === 'select' && key === item.prop) {
					const obj = item.columns.find(i => i.text === modelData[key])
					console.log(obj);
					modelData[key] = obj.value

				}
			})
		}
		return modelData
	}
	//校验
	const verify = () => {
		console.log('dddd');
		return new Promise(resolve => {
			uFormRef.value.validate().then(valid => {
				if (valid) {
					const modelData = forMatValue()
					resolve(modelData)
				} else {
					resolve(false)
				}
			}).catch(err => {
				resolve(false)
			})
		})
	}

	const getaloneChecked = () => {
		return state.aloneChecked
	}

	defineExpose({
		verify,
		getaloneChecked,
		initData
	})
</script>

<style lang="scss" scoped>
	.Myform {
		width: 100%;
		// background-color: $uni-bg-color;
		// padding: 20rpx 0;
		padding-bottom: 20rpx;

		.Myform-item {
			// padding: 20rpx;
			padding-right: 0;
		}
	}



	::v-deep .u-form-item__body {
		padding: 0;
	}

	::v-deep .u-form-item__body__right__content__slot {
		position: relative;
	}

	::v-deep .u-input__content__subfix-icon {
		margin-right: 30rpx;
	}

	::v-deep .u-checkbox {
		margin-top: 30rpx;
		padding-left: 20rpx;
	}

	// ::v-deep .u-reset-button::after{
	// 	border: 4px solid #fff !important;
	// }
	// ::v-deep .u-input__content__field-wrapper__field {
	// 	padding: 30rpx;
	// 	display: flex;
	// 	align-items: center !important;
	// }

	.input-shadow {
		// padding:30rpx !important;
		box-shadow: 0px 2px 6px 0px rgba(232, 232, 234, 1);
		// box-sizing: border-box;
	}

	.button {

		position: absolute;
		right: 0;
		top: 100rpx;
		border-color: #505efa;
		color: #505efa;
		// margin: 0;
		font-weight: 900;
		// border: 1px solid red !important;
		// padding: 0;
	}
</style>